// src/main/auth-service.js
const AuthenticationSystem = require('./auth');
const crypto = require('crypto');

class AuthService {
  constructor() {
    this.auth = new AuthenticationSystem();
    this.activeSessions = new Map(); // 内存中存储活跃会话
  }

  // 初始化认证系统
  async initialize() {
    try {
      // 检查是否是第一次运行
      const isFirstRun = await this.checkFirstRun();
      return { isFirstRun };
    } catch (error) {
      console.error('认证系统初始化失败:', error);
      throw error;
    }
  }

  // 检查是否是第一次运行
  async checkFirstRun() {
    // 这里可以检查数据库文件是否存在，或者查询用户表
    const fs = require('fs');
    const path = require('path');
    const dbPath = path.join(__dirname, '..', 'data', 'secure-discipline.sqlite');
    return !fs.existsSync(dbPath);
  }

  // 处理首次设置
  async handleFirstTimeSetup(username, password) {
    try {
      const userId = await this.auth.registerFirstUser(username, password);
      return { success: true, userId };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // 处理用户登录
  async handleLogin(username, password, ipAddress = '127.0.0.1') {
    try {
      const result = await this.auth.login(username, password, ipAddress, 'Electron App');
      
      // 存储会话到内存
      this.activeSessions.set(result.sessionToken, {
        userId: result.user.id,
        username: result.user.username,
        lastActivity: Date.now(),
        expiresAt: result.expiresAt
      });

      return { success: true, ...result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // 验证会话
  async verifySession(sessionToken, ipAddress = '127.0.0.1') {
    try {
      const userInfo = await this.auth.verifySession(sessionToken, ipAddress);
      
      // 更新最后活动时间
      if (this.activeSessions.has(sessionToken)) {
        const session = this.activeSessions.get(sessionToken);
        session.lastActivity = Date.now();
        this.activeSessions.set(sessionToken, session);
      }

      return { success: true, user: userInfo };
    } catch (error) {
      // 会话无效，从内存中移除
      this.activeSessions.delete(sessionToken);
      return { success: false, error: error.message };
    }
  }

  // 用户登出
  async handleLogout(sessionToken) {
    try {
      await this.auth.logout(sessionToken);
      this.activeSessions.delete(sessionToken);
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // 检查会话是否过期（5分钟无操作）
  checkSessionTimeout(sessionToken) {
    const session = this.activeSessions.get(sessionToken);
    if (!session) return true;

    const inactiveTime = Date.now() - session.lastActivity;
    return inactiveTime > (5 * 60 * 1000); // 5分钟
  }

  // 清理过期会话
  cleanupExpiredSessions() {
    for (const [token, session] of this.activeSessions.entries()) {
      if (Date.now() > new Date(session.expiresAt).getTime()) {
        this.activeSessions.delete(token);
      }
    }
  }
}

module.exports = AuthService;